import { useState, useEffect } from 'react'
import { IconContext } from 'react-icons'
import { BsArrowLeft } from 'react-icons/bs'
import { useHistory } from 'react-router-dom'
import styles from './Archive.module.css'

const Archive = () => {
  const history = useHistory()
  const returnToNavigate = () => {
    history.push("/navigation")
  }
  const [ data, setData ] = useState(null)
  const getData = async () => {
    const response = await fetch("http://localhost:3003/articles/byDate")
    const result = await response.json()
    const tmpMap = new Map()
    result.forEach(item => {
      item.createTime = (new Date(item.createTime)).toLocaleDateString()
      if (!tmpMap.has(item.createTime)) {
        tmpMap.set(item.createTime,[])
      } else {
        tmpMap.get(item.createTime).push(item)
      }
    })
    setData(Array.from(tmpMap))
  }
  useEffect(() => {
    getData()
  // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [])
  return (
    <div className={styles.archive}>
      <div className={styles.header}>
        <IconContext.Provider value={{ color: "#666", size: "2rem"}}>
          <div style={{ cursor: "pointer"}} onClick={ () => returnToNavigate()}>
            <BsArrowLeft />
          </div>
        </IconContext.Provider>
      </div>
      <div className={styles.inner}>
      {
        data && data.map((dateItem,index) => {
          return (
            <div key={index} className={styles.dateItem}>
              <h2 className={styles.date}>{dateItem[0]}</h2>
              {
                dateItem[1].map((article,index) => <div key={index} className={styles.title}>{article.title}</div>)
              }
            </div>
          )
        })
      }
      </div>
    </div>
  )
}

export default Archive